package com.aj.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.aj.activity.dialog.UpdateDialog;
import com.aj.activity.dialog.UpdateDialog.IUpdateDialog;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.AccountDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.User;
import com.aj.databases.entry.VersionInfo;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.LoginRequest;
import com.aj.http.request.UpdateRequest;
import com.aj.http.request.UploadJPushChannelRequest;
import com.aj.http.request.UserInfoRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.LoginRespons;
import com.aj.http.response.UpdateResponse;
import com.aj.http.response.UserResponse;
import com.aj.sharepreferences.LoveHomeSharedPreferences;
import com.aj.utils.Contants;
import com.aj.utils.DesBase64Tool;
import com.aj.utils.MobileUtil;
import com.aj.utils.StringUtils;
import com.easemob.EMCallBack;
import com.easemob.applib.controller.HXSDKHelper;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.umeng.analytics.MobclickAgent;

public class WelcomeActivity extends Activity {
	private static final String TAG = WelcomeActivity.class.getName();

	private UpdateDialog updateDialog;

	private ProgressBar mProgress;

	private AlertDialog downloadDialog;

	private boolean interceptFlag = false;

	private VersionInfo versionInfo;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private String saveFileName;

	private Thread downLoadThread;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onStart() {
		super.onStart();
		// umeng
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// onresume时，取消notification显示
		HXSDKHelper.getInstance().getNotifier().reset();
		JPushInterface.onResume(this);
		// umeng
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.excute(this, MobileUtil.getVersionName(this),
				new IHttpCallBack() {
					@Override
					public void success(String result) {
						try {
							UpdateResponse updateResponse = new UpdateResponse(
									new JSONObject(result));
							if (updateResponse
									.getCommon()
									.getReturnCode()
									.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
								versionInfo = updateResponse.getVersionInfo();
								String versionID = versionInfo.getClientVer();
								if (StringUtils.compare(versionID, MobileUtil
										.getVersionName(WelcomeActivity.this)) > 1) {
									String message = versionInfo
											.getUpdateContent() == null
											|| versionInfo.getUpdateContent()
													.trim().length() == 0 ? getString(R.string.no_updateinfo_text)
											: versionInfo.getUpdateContent();
									showUpdateDialog(
											message,
											(versionInfo.getForceUpdate() == null
													|| versionInfo
															.getForceUpdate()
															.trim().equals("N") ? false
													: true));
								}
							} else {
								final AccountDao accountDao = new AccountDao(
										WelcomeActivity.this);
								final Account account = accountDao.getOne();
								if (account != null
										&& account.getPassword() != null
										&& account.getPassword().trim()
												.length() > 0) {
									// TODO 登录
									LoginRequest loginRequest = new LoginRequest();
									loginRequest.excute(WelcomeActivity.this,
											account.getPhone(),
											account.getPassword(),
											new IHttpCallBack() {
												@Override
												public void success(
														String result) {
													try {
														LoginRespons loginRespons = new LoginRespons(
																new JSONObject(
																		result));
														Common common = loginRespons
																.getCommon();
														if (common != null
																&& common
																		.getReturnCode() != null
																&& common
																		.getReturnCode()
																		.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
															account.setLast_used_user_id(loginRespons
																	.getAccount()
																	.getLast_used_user_id());
															account.setToken(loginRespons
																	.getAccount()
																	.getToken());
															account.setLastlogin_time(new Date());
															accountDao
																	.update(account);
															LoveHomeApplication.token = account
																	.getToken();
															UserInfoRequest userInfoRequest = new UserInfoRequest();
															userInfoRequest
																	.excute(WelcomeActivity.this,
																			account.getLast_used_user_id(),
																			new IHttpCallBack() {
																				@Override
																				public void success(
																						String result) {
																					try {
																						UserResponse userResponse = new UserResponse(
																								new JSONObject(
																										result));
																						final User user = userResponse
																								.getUser();
																						UserDao userDao = new UserDao(
																								WelcomeActivity.this);
																						userDao.insertUser(user);
																						// 上传JPush别名
																						// 成功
																						new UploadJPushChannelRequest()
																								.excute(WelcomeActivity.this,
																										user.getUser_id(),
																										JPushInterface
																												.getRegistrationID(LoveHomeApplication.application),
																										new IHttpCallBack() {
																											@Override
																											public void success(
																													String result) {

																												Log.e(TAG,
																														"result:"
																																+ result);
																											}

																											@Override
																											public void fail(
																													String result) {
																												Log.e(TAG,
																														"result:"
																																+ result);

																											}
																										});
																						// 登录环信
																						if (!DemoHXSDKHelper
																								.getInstance()
																								.isLogined()) {
																							String userName = user
																									.getUser_id();
																							String password = DesBase64Tool
																									.encryptDES("aj2015");
																							EMChatManager
																									.getInstance()
																									.login(userName,
																											password,
																											new EMCallBack() {

																												@Override
																												public void onSuccess() {
																													// 登陆成功，保存用户名密码
																													LoveHomeApplication.application
																															.setUserName(account
																																	.getLast_used_user_id());
																													LoveHomeApplication.application
																															.setPassword(account
																																	.getPassword());

																													try {
																														// **
																														// 第一次登录或者之前logout后再登录，加载所有本地群和回话
																														// **
																														// manually
																														// load
																														// all
																														// local
																														// groups
																														// and
																														EMGroupManager
																																.getInstance()
																																.loadAllGroups();
																														EMChatManager
																																.getInstance()
																																.loadAllConversations();
																														// 处理好友和群组
																														// initializeContacts();
																													} catch (Exception e) {
																														e.printStackTrace();
																														// 取好友或者群聊失败，不让进入主页面
																														runOnUiThread(new Runnable() {
																															@Override
																															public void run() {
																																DemoHXSDKHelper
																																		.getInstance()
																																		.logout(true,
																																				null);
																																Toast.makeText(
																																		getApplicationContext(),
																																		R.string.login_failure_failed,
																																		1)
																																		.show();
																															}
																														});
																														return;
																													}
																													// 更新当前用户的nickname
																													// 此方法的作用是在ios离线推送时能够显示用户nick
																													boolean updatenick = EMChatManager
																															.getInstance()
																															.updateCurrentUserNick(
																																	LoveHomeApplication.currentUserNick
																																			.trim());
																													if (!updatenick) {
																														Log.e("LoginActivity",
																																"update current user nick fail");
																													}
																													// //
																													// 进入主页面
																													// Intent
																													// intent
																													// =
																													// new
																													// Intent(
																													// LoginActivity.this,
																													// MainActivity.class);
																													// startActivity(intent);
																													//
																													// finish();
																												}

																												@Override
																												public void onProgress(
																														int progress,
																														String status) {
																												}

																												@Override
																												public void onError(
																														final int code,
																														final String message) {
																													// if
																													// (!progressShow)
																													// {
																													// return;
																													// }
																													runOnUiThread(new Runnable() {
																														@Override
																														public void run() {
																															// pd.dismiss();
																															Toast.makeText(
																																	getApplicationContext(),
																																	getString(R.string.Login_failed)
																																			+ message,
																																	Toast.LENGTH_SHORT)
																																	.show();
																														}
																													});
																												}
																											});
																						}
																					} catch (JSONException e) {
																						e.printStackTrace();
																					}
																					gotoHomePage();
																				}

																				@Override
																				public void fail(
																						String result) {
																					gotoHomePage();
																				}
																			});
														} else {
															gotoHomePage();
														}
													} catch (JSONException e) {
														e.printStackTrace();
													}
												}

												@Override
												public void fail(String result) {
													gotoHomePage();
												}
											});
								} else {
									gotoHomePage();
								}
							}
						} catch (JSONException e) {
							Log.e(TAG, "ERROR:" + result, e);
							e.printStackTrace();
							gotoHomePage();
						}
					}

					@Override
					public void fail(String result) {
						Log.e(TAG, "ERROR:" + result);
						gotoHomePage();
					}
				});
	}

	private void gotoHomePage() {
		Intent intent = null;
		if (!LoveHomeSharedPreferences.getWelcomeGuideFlag()) {
			intent = new Intent(Contants.GUIDEACTIVITY_ACTION);
		} else {
			intent = new Intent(Contants.HOMEACTIVITY_ACTION);
		}
		startActivity(intent);
		finish();
	}

	private void showUpdateDialog(String message, final boolean isForceUpdate) {
		if (updateDialog == null) {
			updateDialog = new UpdateDialog(this);
		}
		updateDialog.show();
		updateDialog.setContent(message);
		updateDialog.setUpdateDialogInterface(new IUpdateDialog() {
			@Override
			public void sureInfo() {
				// TODO 下载APP
				showDownloadDialog();
			}

			@Override
			public void cannelInfo() {
				if (isForceUpdate) {
					finish();
				} else {
					// TODO 执行登录或者直接跳转到主页面操作
				}
			}
		});
	}

	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			Intent intent = null;
			if (!LoveHomeSharedPreferences.getWelcomeGuideFlag()) {
				intent = new Intent(Contants.GUIDEACTIVITY_ACTION);
			} else {
				intent = new Intent(Contants.LOGINACTIVITY_ACTION);
			}
			startActivity(intent);
			finish();
			return true;
		}
	});

	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("软件版本更新中");
		final LayoutInflater inflater = LayoutInflater.from(this);
		View v = inflater.inflate(R.layout.dialog_update_process, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		builder.setView(v);
		downloadDialog = builder.create();
		downloadDialog.setCancelable(false);
		downloadDialog.show();

		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(versionInfo.getClientUrl());

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				InputStream is = conn.getInputStream();
				long fileSize = Long.parseLong(conn
						.getHeaderField("Content-length") == null ? "1" : conn
						.getHeaderField("Content-length").toString());
				long length = fileSize;
				File file = new File(Contants.APP_PATH);
				if (!file.exists()) {
					file.mkdir();
				}
				saveFileName = Contants.APP_PATH + "LoveHome.apk";
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				if (ApkFile.exists()) {
					ApkFile.delete();
				}
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						interceptFlag = true;
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		this.startActivity(i);
		android.os.Process.killProcess(android.os.Process.myPid());

	}
}
